{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce5e76a5-222b-408d-b90c-19a801432e66",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - ReAct\n",
    "\n",
    "ReAct 核心思想是 推理+操作，本示例以` Google Search` 和 `LLM Math` 作为可选操作集合（toolkits），实现 ReAct 功能。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cd59da96-dda8-42c8-9c82-8460cf3aa75d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 更换为自己的 Serp API KEY\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"1e3c93e0753ac224098370cd71da86150c6609caba6b5aaa307e04b72a5006e1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d03a5086-d453-44f2-898b-0fecb746d0c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.llms import OpenAI\n",
    "\n",
    "llm = OpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9e7e7202-625a-4cec-999a-321a40115792",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "#加载 LangChain 内置的 Tools\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d89d569f-5313-42f3-8f1a-ea45fb1ea035",
   "metadata": {},
   "source": [
    "### 使用语言模型（GPT-3）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "70af3538-18c4-4c64-99a7-96b32038d31b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实例化 ZERO_SHOT_REACT Agent\n",
    "agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "484bba88-885b-4630-a9a9-b2ff6241df83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I need to find out who Leonardo DiCaprio's girlfriend is and then calculate her age to the 0.43 power.\n",
      "Action: Search\n",
      "Action Input: \"Leonardo DiCaprio girlfriend\"\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mVittoria Ceretti: 2023 According to sources, Leo and Vittoria reportedly met during the Killers of the Flower Moon premiere at the 2023 Cannes Film Festival. (The actor stars in the Martin Scorsese–directed film opposite Lily Gladstone.)\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I need to calculate Vittoria's age to the 0.43 power.\n",
      "Action: Calculator\n",
      "Action Input: 2023^0.43\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 26.39843795372203\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
      "Final Answer: Vittoria Ceretti的年龄的0.43次方是26.39843795372203。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Vittoria Ceretti的年龄的0.43次方是26.39843795372203。'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b816038d-6f3a-47cb-b614-e432db8c1883",
   "metadata": {},
   "source": [
    "### 使用聊天模型（GPT-4）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "448c877f-577b-4277-a155-51223dc3d949",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mQuestion: 谁是莱昂纳多·迪卡普里奥的女朋友？\n",
      "Thought: 首先，我需要找出莱昂纳多·迪卡普里奥当前的女朋友是谁。这是一个关于当前事件的问题，所以我将使用搜索工具来找到答案。\n",
      "Action:\n",
      "```json\n",
      "{\n",
      "  \"action\": \"Search\",\n",
      "  \"action_input\": \"莱昂纳多·迪卡普里奥 当前女朋友\"\n",
      "}\n",
      "```\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m['刚和25岁超模女友卡米拉分手的小李子莱昂纳多·迪卡普里奥，被曝22岁新女友“火速上线”。 这位被换女友如换衣服的小李子“临幸”的妙龄女子就是乌克兰超模玛莉 ...', '8月31日，据外媒报道，47岁的莱昂纳多·迪卡普里奥与刚满25岁不久的模特女友卡米拉·莫罗在今年刚刚入夏的时候，以“顺其自然”的方式分手，5年感情画上 ...', '49岁的莱昂纳多·迪卡普里奥和25岁女友Vittoria Ceretti及其女友的家人现身伦敦。ps：大胆的预测一下，小李子不会要结婚了吧？ \\u200b', '新浪娱乐讯据媒体报道，48岁的奥斯卡影帝——莱昂纳多·迪卡普里奥（Leonardo DiCaprio）上周被拍到和23岁的女演员维多利亚·拉马斯（Victoria Lamas） ...', '莱昂纳多·迪卡普里奥(Leonardo DiCaprio) 和梅根·罗奇(Meghan Roche) 在看到豪华游艇后，否认“不，我们没有订婚”。', '8月31日，据外媒报道，“小李子”莱昂纳多·迪卡普里奥最近又双叒叕分手了，正式与辣妹模特卡米拉·莫罗尼结束近5年恋情。圈内有一种传闻，“小李子”的女友不会 ...', '现任女友是阿根廷模特和女演员卡米拉·莫朗（Camila Morrone），今年刚满22岁，她的年龄竟然与电影《泰坦尼克号》相同，她的男友小李在1997年凭借这部电影 ...', '演艺经历 1979年，5岁时，莱昂纳多·迪卡普里奥迎来了他的电视银幕处女秀，在教育片《游戏屋》中扮演一个角色。1988年，14岁时，他出现在他的第一部商业广告之中，那是为 ...', '莱昂纳多·迪卡普里奥再度分手，又一个没超过25岁的女友 ... 两人从2018年开始交往，至今已经交往了4年多。然而，今年5月被偷拍的狗仔队却发现两人关系出现 ...']\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m根据搜索结果，莱昂纳多·迪卡普里奥最近的女朋友是22岁的乌克兰超模玛莉。现在我需要计算22岁的0.43次方是多少。\n",
      "\n",
      "Action:\n",
      "```json\n",
      "{\n",
      "  \"action\": \"Calculator\",\n",
      "  \"action_input\": {\n",
      "    \"expression\": \"22^0.43\"\n",
      "  }\n",
      "}\n",
      "```\n",
      "\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.777824273683966\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mI now know the final answer to the original input question.\n",
      "\n",
      "Final Answer: 莱昂纳多·迪卡普里奥的女朋友是22岁的乌克兰超模玛莉，她现在年龄的0.43次方是大约3.78。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'莱昂纳多·迪卡普里奥的女朋友是22岁的乌克兰超模玛莉，她现在年龄的0.43次方是大约3.78。'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4-1106-preview\", temperature=0)\n",
    "agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f4728e-bf1f-4643-a2ee-8f8679ddc58a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
